import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:get/get.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/assessments.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/controller/homeworks.dart';
import 'package:ichinesereader/controller/reports.dart';
import 'package:ichinesereader/controller/schooladmin.dart';
import 'package:ichinesereader/controller/user.dart';
import 'package:ichinesereader/models/assessment/assessmentQueryDto.dart';
import 'package:ichinesereader/models/assessment/assessmentTeacherQueryDto.dart';
import 'package:ichinesereader/models/student/assignmentSearchDto.dart';
import 'package:ichinesereader/models/teacher/AssignmentType.dart';
import 'package:ichinesereader/models/teacher/TeacherClass.dart';
import 'package:ichinesereader/pages/teacher/assessments.dart';
import 'package:ichinesereader/pages/teacher/evaluationHome.dart';
import 'package:ichinesereader/pages/teacher/homework.dart';
import 'package:ichinesereader/pages/teacher/reports.dart';
import 'package:ichinesereader/utils/log.dart';
import '../../controller/evaluation.dart';
import '../../models/assessment/assessmentBookType.dart';
import '../../themes/appTheme.dart';
import 'package:universal_html/html.dart' as UHtml;

class SwitchTeacherClassDialog extends StatefulWidget {
  SwitchTeacherClassDialog({
    Key? key,
  }) : super(key: key);

  _SwitchTeacherClassDialogState createState() =>
      new _SwitchTeacherClassDialogState();
}

class _SwitchTeacherClassDialogState extends State<SwitchTeacherClassDialog> {
  var box = Hive.box('appconfig');
  final SchoolAdminController _schoolAdminController = Get.find();
  final UserController _userController = Get.find();
  String _classId = '';

  void saveSharedCurrentClassId(String classId) async {
    box.put('nanhaiV4.8TeacherClassSelected', classId);
  }

  @override
  void initState() {
    _classId = box.get(CacheManagerKey['currentclass'].toString()) ?? '';
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            'Please Choose Class'.tr,
            style: TextStyle(
                fontSize: 30.0,
                decoration: TextDecoration.underline,
                decorationStyle: TextDecorationStyle.dotted),
          ),
          InkWell(
            onTap: () {
              Navigator.of(context).pop();
            },
            child: Icon(Icons.cancel,
                color: Get.isDarkMode ? Colors.white : Colors.blueGrey),
          ),
        ],
      ),
      titleTextStyle: TextStyle(
          letterSpacing: 1,
          color: Get.isDarkMode ? Get.theme.primaryColorDark : Colors.blueGrey,
          decoration: TextDecoration.underline,
          decorationStyle: TextDecorationStyle.dotted,
          fontSize: 21.0),
      backgroundColor:
          Get.isDarkMode ? AppTheme.colors.darkTheme2 : Colors.white,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.all(
          Radius.circular(6.0),
        ),
      ),
      content: Container(
        width: 450,
        height: 300,
        child: Column(children: [
          Container(
            child: FormBuilder(
              child: FormBuilderChoiceChip(
                crossAxisAlignment: WrapCrossAlignment.start,
                runSpacing: 3.0,
                spacing: 6.0,
                decoration: InputDecoration(
                  prefixIcon: Padding(
                    padding: const EdgeInsets.all(2.0),
                    child: Tooltip(
                        message: 'Choose Class'.tr,
                        child: Icon(Icons.class_rounded)),
                  ),
                  prefixIconColor:
                      Get.isDarkMode ? Get.theme.primaryColorDark : Colors.blueGrey,
                ),
                backgroundColor:
                    Get.isDarkMode ? Get.theme.primaryColor : Colors.grey,
                selectedColor: Get.isDarkMode
                    ? Colors.white
                    : Theme.of(context).primaryColorDark,
                initialValue: _userController.myClasses
                    .firstWhere((element) => element.classId == _classId),
                name: 'teacherclass_chip',
                onChanged: (value) {
                  if (value == null) return;
                  try {
                    _userController.setCurrentClass(value as TeacherClass);
                    saveSharedCurrentClassId(value.classId.toString());
                    _schoolAdminController.fetchClassDetailsNewByClassId(
                        value.classId.toString());
                    box.put(CacheManagerKey['currentclass'].toString(),
                        value.classId);
                    if (GetPlatform.isWeb) {
                      UHtml.document.cookie =
                          "nanhaiV4.8TeacherClassSelected=${value.classId.toString()};path=/";
                    }

                    if (Get.currentRoute == '/teacher/reports' &&
                        teacherReportsTabController.index == 0) {
                      final ReportsController _reportsController = Get.find();
                      _reportsController.fetchClassProficiencyLevelData(
                          value.classId.toString());
                      _reportsController.fetchClassSkillsData(
                          value.classId.toString(), false);
                      _reportsController.fetchClassOverviewTotalData(
                          value.classId.toString(), null, null);
                    }
                    if (Get.currentRoute == '/teacher/reports' &&
                        teacherReportsTabController.index == 1) {
                      final ReportsController _reportsController = Get.find();
                      _reportsController.fetchClassOverviewDetails(
                          value.classId.toString(), null, null);
                    }
                    if (Get.currentRoute == '/teacher/reports' &&
                        teacherReportsTabController.index == 3) {
                      var dto = new AssignmentSearchDto();
                      final ReportsController _reportsController = Get.find();
                      dto.assignmentType = 'ASSIGNMENT';
                      dto.past = true;
                      dto.live = true;
                      dto.sortField = "-created";
                      _reportsController.fetchClassAssignmentsData(
                          value.classId.toString(), dto);
                    }
                    if (Get.currentRoute == '/teacher/reports' &&
                        teacherReportsTabController.index == 2) {
                      final ReportsController _reportsController = Get.find();
                      _reportsController.fetchTeacherBaskets(
                          value.classId.toString(), [], []);
                    }
                    if (Get.currentRoute == '/teacher/reports' &&
                        teacherReportsTabController.index == 4) {
                      final ReportsController _reportsController = Get.find();
                      _reportsController.getQuizBookRecordsByClass(
                          value.classId.toString(), "", "", "");
                    }
                    if (Get.currentRoute == '/teacher/reports' &&
                        teacherReportsTabController.index == 5) {
                      /// skill center
                      final ReportsController _reportsController = Get.find();
                      int _currentLevel = 1;
                      try {
                        _currentLevel = (box.get(
                                CacheManagerKey['eveluationlevel'].toString(),
                                defaultValue: 1) as double)
                            .toInt();
                      } catch (error) {
                        _currentLevel = 1;
                      }
                      _reportsController.fetchLibraryKnowledgeClassData(
                          _classId, _currentLevel.toString());
                    }

                    ///assessments
                    if (Get.currentRoute == '/teacher/assessments' &&
                        teacherAssessmentTabController.index == 0) {
                      final AssessmentsController _assessmentsController =
                          Get.find();
                      AssessmentQueryDto dto = new AssessmentQueryDto();
                      dto.live = true;
                      dto.queued = true;
                      dto.past = false;
                      _assessmentsController.fetchAssessmentsByClass(
                          _classId, dto);
                    }

                    if (Get.currentRoute == '/teacher/assessments' &&
                        teacherAssessmentTabController.index == 1) {
                      final AssessmentsController _assessmentsController =
                          Get.find();
                      AssessmentBookType type =
                          Constants.assessmentBookTypes[0];
                      _assessmentsController.setCurrentAssessmenbBookType(type);
                      _assessmentsController.fetchAssessmentBenchmarkBooks(
                          '0', '0', type.assessmentType, '');
                    }

                    if (Get.currentRoute == '/teacher/assessments' &&
                        teacherAssessmentTabController.index == 2) {
                      final ReportsController _reportsController = Get.find();
                      AssessmentTeacherQueryDto dto =
                          new AssessmentTeacherQueryDto(status: [], type: []);
                      _reportsController.fetchTeacherAssessmentRecords(
                          value.classId.toString(), dto);
                    }

                    if (Get.currentRoute == '/teacher/students') {
                      _schoolAdminController.fetchSchoolStudentsByClassId(
                          value.classId.toString(), true);
                    }

                    if (Get.currentRoute == '/teacher/homework' &&
                        teacherHomeworkTabController.index == 0) {
                      final HomeworksController _homeworkController =
                          Get.find();
                      AssignmentType _assignmentType = AssignmentType();
                      _assignmentType.assignmentType = 'ASSIGNMENT';
                      _assignmentType.live = true;
                      _assignmentType.queued = true;
                      _assignmentType.past = false;

                      _homeworkController.fetchTeacherHomworks(
                          value.classId.toString(), _assignmentType);
                    }

                    if (Get.currentRoute == '/teacher/homework' &&
                        teacherHomeworkTabController.index == 1) {
                      final ReportsController _reportsController = Get.find();
                      String classId =
                          box.get(CacheManagerKey['currentclass'].toString());
                      Future.delayed(Duration(milliseconds: 100), (() {
                        AssignmentSearchDto dto = AssignmentSearchDto();
                        dto.assignmentType = 'ASSIGNMENT';
                        dto.past = true;
                        dto.live = true;
                        dto.sortField = "-created";
                        _reportsController.fetchClassAssignmentsData(
                            classId, dto);
                      }));
                    }

                    // for evaluations
                    if (Get.currentRoute == '/teacher/evaluation' &&
                        teacherEvaluationTabController.index == 0) {
                      final EvaluationController evaController = Get.find();
                      int _currentLevel = 1;
                      try {
                        _currentLevel = (box.get(
                                CacheManagerKey['eveluationlevel'].toString(),
                                defaultValue: 1) as double)
                            .toInt();
                      } catch (error) {
                        _currentLevel = 1;
                      }
                      evaController.fetchEvaluationBooks('0', '0', 'EVALUATION',
                          _currentLevel.toString(), value.classId.toString());
                    }
                    if (Get.currentRoute == '/teacher/evaluation' &&
                        teacherEvaluationTabController.index == 1) {
                      // switch class is not necessary for tests books currently because there is no any diffrence
                      final AssessmentsController _controller = Get.find();
                      AssessmentBookType type =
                          _controller.getCurrentAssessmentBookType();
                      _controller.fetchAssessmentBenchmarkBooks(
                          '0', '0', type.assessmentType, '');
                    } else if (Get.currentRoute == '/teacher/evaluation' &&
                        teacherEvaluationTabController.index == 2) {
                      final EvaluationController evaController = Get.find();
                      evaController.fetchEvaluationRecords(
                          '0', '0', '', value.classId.toString());
                    }
                    if (Get.currentRoute == '/teacher/evaluation' &&
                        teacherEvaluationTabController.index == 3) {
                      int _currentLevel = 1;
                      final EvaluationController evaController = Get.find();
                      try {
                       _currentLevel = (box.get(
                                CacheManagerKey['eveluationlevel'].toString(),
                                defaultValue: 1) as double)
                            .toInt();
                      } catch (error) {
                        _currentLevel = 1;
                      }
                      evaController.fetchEvaluationClassReportData(
                          value.classId.toString(), _currentLevel.toString());
                    }
                    if (Get.currentRoute == '/teacher/evaluation' &&
                        teacherEvaluationTabController.index == 4) {
                      int _currentLevel = 1;
                      final EvaluationController evaController = Get.find();
                      try {
                        _currentLevel = (box.get(
                                CacheManagerKey['eveluationlevel'].toString(),
                                defaultValue: 1) as double)
                            .toInt();
                      } catch (error) {
                        _currentLevel = 1;
                      }
                      var skillType = box.get('SkillType');
                      if (skillType == 'Proficient')
                        evaController.fetchEvaluationProficiencySkillsData(
                            value.classId.toString(),
                            _currentLevel.toString(),
                            '');
                      else if (skillType == 'Linguistics')
                        evaController.fetchEvaluationLinguisticKnowledgesData(
                            value.classId.toString(),
                            _currentLevel.toString(),
                            '');
                      else if (skillType == 'LanguageSkill')
                        evaController.fetchEvaluationSkillPointsData(
                            value.classId.toString(), _currentLevel.toString());
                      else if (skillType == 'Report')
                        evaController.fetchEvaluationClassReportData(
                            value.classId.toString(), _currentLevel.toString());
                    }
                  } catch (error) {
                    Log.debug(error);
                  }
                },
                options: _userController.myClasses
                    .map((teacherclass) => FormBuilderChipOption<TeacherClass>(
                          value: teacherclass,
                          child: Text(
                            teacherclass.className.toString(),
                            textAlign: TextAlign.center,
                            style: TextStyle(
                              color:
                                  Get.isDarkMode ? Colors.black : Colors.white,
                              fontSize: 15,
                              letterSpacing: 1,
                            ),
                            overflow: TextOverflow.ellipsis,
                          ),
                        ))
                    .toList(),
              ),
            ),
          ),
        ]),
      ),
    );
  }
}
